package com.newworld.dmsapp2.activity;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.fragment.bean.UpdateApp;
import com.newworld.dmsapp2.ui.view.CustomDialog;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;
import com.pgyersdk.feedback.PgyFeedback;

public class SettingSoftwareVersionActivity extends Activity implements
		OnClickListener {
	private ImageButton titlebar_left_software_version;
	private Button version_check_update;
	private Button version_tell_us;
	private TextView present_version_record;
	private CustomDialog dialog;
	// 更新版本号
	private String updateVersionCode;
	// 更新版本名
	@SuppressWarnings("unused")
	private String updateVersionName;
	// 更新软件url
	public static String updateUrl;
	// 软件名
	@SuppressWarnings("unused")
	private String appName;
	// 是否更新本地数据库 1:更新 0：不更新
	@SuppressWarnings("unused")
	private String updateData;
	// 最新的app版本的appKey
	private String appKey;
	private UpdateApp app = new UpdateApp();
	
	private String sessionId;

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case Config.HANDLER_MSG_APP_DIFINE_SUCCESS:
				updateData = "0";
				UpdateApp getapp = (UpdateApp) msg.obj;
				appKey = getapp.getAppKey();
				appName = getapp.getAppFileName();
				updateVersionName = getapp.getAppVersion();
				updateVersionCode = getapp.getAppVersionNo();
				updateUrl = Tool.getConfigUrl(Config.SERVER_URL, Config.APP_DWONLOAD_APK) + "?" + "_api_key="
						+ Config.APP_API_KEY + "&" + "aKey=" + appKey;
				// dialog.dismiss();
				Bundle bundle = new Bundle();
				bundle.putString(Config.APP_UPDATEURL, updateUrl);
				bundle.putString(Config.APP_UPDATE_VERSIONCODE,
						updateVersionCode);
				Intent intent1 = new Intent(
						SettingSoftwareVersionActivity.this,
						WebViewMainActivity.class);
				intent1.putExtras(bundle);
				startActivity(intent1);
				finish();
				/*
				 * UpdateManager manager = new UpdateManager(
				 * SettingSoftwareVersionActivity.this, updateVersionCode,
				 * updateVersionName, updateUrl, appName,updateData);
				 * manager.checkUpdate();
				 */
				// 检查软件更新

				Toast.makeText(SettingSoftwareVersionActivity.this,
						"验证app版本成功", Toast.LENGTH_SHORT).show();
				break;
			case Config.HANDLER_MSG_APP_DIFINE_FAIL:
				dialog.dismiss();
				Toast.makeText(SettingSoftwareVersionActivity.this,
						(String) msg.obj, Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_set_software_update);
		initData();
		titlebar_left_software_version = (ImageButton) findViewById(R.id.titlebar_left_software_version);
		version_check_update = (Button) findViewById(R.id.version_check_update);
		version_tell_us = (Button)findViewById(R.id.version_tell_us);
		present_version_record = (TextView) findViewById(R.id.present_version_record);
		titlebar_left_software_version.setOnClickListener(this);
		version_check_update.setOnClickListener(this);
		version_tell_us.setOnClickListener(this);
		try {
			present_version_record.setText(getVersionName());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initData(){
		User user = SingleSample.getInstance(SettingSoftwareVersionActivity.this).getUser();
		if(null != user){
			if(null != user.getSessionId() && !user.getSessionId().equals("")){
				sessionId = user.getSessionId();
			}
		}
	}
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.titlebar_left_software_version:
			onBackPressed();
			/*
			 * Intent intent1 = new Intent();
			 * intent1.setClass(SettingCacheActivity.this,
			 * SettingActivity.class); startActivity(intent1);
			 */
			break;
		case R.id.version_check_update:
			// 标准的对话框封装
			/*
			 * dialog = new CustomDialog( SettingSoftwareVersionActivity.this);
			 * dialog.setTitle("版本更新信息"); dialog.setDetial("是否确定更新软件版本");
			 * dialog.setLeftOnClick(new OnClickListener() {
			 * 
			 * @Override public void onClick(View v) { dialog.dismiss(); } });
			 * dialog.show(); dialog.setRightOnClick(new OnClickListener() {
			 * 
			 * @Override public void onClick(View v) {
			 * 
			 * new defineApp().start(); dialog.dismiss(); Bundle bundle = new
			 * Bundle(); bundle.putString(Config.APP_UPDATEURL, updateUrl);
			 * Intent intent1 = new Intent(SettingSoftwareVersionActivity.this,
			 * WebViewMainActivity.class); intent1.putExtras(bundle);
			 * startActivity(intent1); } }); dialog.show();
			 */
			new defineApp().start();
		case R.id.version_tell_us:
			// 打开沉浸式
			PgyFeedback.getInstance().showDialog(SettingSoftwareVersionActivity.this);
		default:
			break;
		}
	}

	// 获取软件当前版本号
	private String getVersionName() throws Exception {
		// 获取packagemanager的实例
		PackageManager packageManager = getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),
				0);
		String version = packInfo.versionName;
		return version;
	}

	// 验证App短链接

	class defineApp extends Thread {
		public HashMap<String, String> orderList;
		public HashMap<String, String> searchList;
		public String curPage;
		public String search = "";

		public defineApp() {
			super();

		}

		@Override
		public void run() {

			if (Tool.isNetworkAvailable(SettingSoftwareVersionActivity.this)) {
				try {
					String result = null;
					String url = Config.APP_DEFINE_URL;
					Map<String, String> map = new HashMap<String, String>();
					map.put("shortcut", Config.APP_SHORT_CUT);
					map.put("_api_key", Config.APP_API_KEY);
					
					result = HttpUtil.postRequestSe(url, map,sessionId);
					result = result.replace("rows", "tasks");
					Log.e("我访问的url是：", url);
					Log.e("我访问shortcut的是：", map.get("shortcut"));
					Log.e("我访问_api_key的是：", map.get("_api_key"));
					Log.e("搜索的result", result);
					JSONObject resulObj = new JSONObject(result);
					String code = resulObj.getString("code");
					String message = resulObj.getString("message");
					String data = resulObj.getString("data");
					if (code.equals("0")) {// 短链接成功
						java.lang.reflect.Type type = new TypeToken<UpdateApp>() {
						}.getType();
						Gson gson = new Gson();
						app = gson.fromJson(data, type);
						/*
						 * appKey = app.getAppKey(); appName =
						 * app.getAppFileName(); updateVersionName =
						 * app.getAppVersion(); updateVersionCode =
						 * app.getAppVersionNo();
						 */
						/*
						 * appKey = new JSONObject(result).getString("appKey");
						 * appName = new
						 * JSONObject(result).getString("appFileName");
						 * updateVersionName = new
						 * JSONObject(result).getString("appVersion");
						 * updateVersionCode = new
						 * JSONObject(result).getString("appVersionNo");
						 */
						mHandler.obtainMessage(
								Config.HANDLER_MSG_APP_DIFINE_SUCCESS, app)
								.sendToTarget();
						// mHandler.obtainMessage(Config.HANDLER_MSG_APP_DIFINE_SUCCESS,
						// message).sendToTarget();
					} else if (code.equals("2")) {// 短链接失败
						mHandler.obtainMessage(
								Config.HANDLER_MSG_APP_DIFINE_FAIL, message)
								.sendToTarget();
					} else {
						mHandler.obtainMessage(
								Config.HANDLER_MSG_APP_DIFINE_FAIL, message)
								.sendToTarget();
					}

				} catch (Exception e) {

					Log.e("SettingSoftwareVersionActivity", "defineApp 网络连接问题");
					/*
					 * Toast.makeText(getActivity(), "网络连接出错" ,
					 * Toast.LENGTH_SHORT).show();
					 */
					e.printStackTrace();
				}
			} else {
				// handler.sendEmptyMessage(1);
			}

		}

	}
}
